/***************************************************************************
 *   Copyright (C) 2008 by Rick Olson   *
 *   rsolson@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "sol.h"
#include <QDebug>
#include <iostream>

namespace solve
{

	Sol::Sol()
	{
	}


	Sol::~Sol()
	{
	}

	std::vector<Element *> Sol::processElements(char *ptr)
	{
		ptr += 16;
		quint16 namelength = ntohs((*(quint16 *)ptr) & 0xffff);
		qDebug() << "namelength: " << namelength;
		ptr += namelength;
		ptr += 4;

		while (ptr) {
			Element *el = new Element();
			ptr = element.extractElement(el, ptr);
			elements.push_back(el);
			//break;
		}

		qDebug() << "Elements: " << elements.size();
/*
		quint8 *_data = new quint8[namelength + 1];
		memset(_data, 0, namelength + 1);
		memcpy(_data, ptr, namelength);
		qDebug() << "name: " << *_data;
*/
/*
		for (quint32 i = *ptr; i <= *ptr + _filesize; i++) {
			std::cout << *ptr;
			*ptr++;
		}

		std::cout << std::endl;
*/
		elements.push_back(new Element());
		return elements;
	}

	void Sol::openFile(const QString filename)
	{
		QFile file(filename);
		if (!file.open( QIODevice::ReadOnly )) {
			throw 52;
		}

		QDataStream in(&file);
		in.setByteOrder(QDataStream::BigEndian);

		char *_memfile = new char[file.size()];
		if (in.readRawData(_memfile, file.size()) == -1) {
			file.close();
			delete _memfile;
			throw 55;
		}

		qDebug() << "Filesize: " << file.size();

		std::cout << std::endl;

		_filesize = file.size();
		_filepointer = 0;
		_filename = file.fileName();

		qDebug() << "Filesize: " << _filesize;
		qDebug() << "Filename: " << _filename;

		file.close();

		processElements(_memfile);
	}


}
